/**
 * Window 配置者
 */
package cn.antia.cwin.window;

import java.util.*;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import cn.antia.cep.common.*;
import cn.antia.cep.common.pool.*;
import cn.antia.cwin.*;
import cn.antia.cep.page.PageRule;
import cn.antia.validation.Validation;

/**
 * @author sunkeei
 * @date Nov 30, 2007
 * @version 0.1
 * @time 
 */
public class WindowConfiger {
	private static Document doc;
	public static int PAGE_SIZE;
	
	static{
		reset();
	}

	/**
	 * 重置
	 */
	public static void reset(){
		SAXReader reader = new SAXReader();
		try{
			doc = reader.read(SysConf.SYSTEM_WINDOW_CONFIG);
			Element element = (Element)doc.selectSingleNode("/all-window/config");
			String sv = element.attributeValue("pageSize");
			if(sv != null){
				PAGE_SIZE = Integer.parseInt(sv);
			}
		}catch(DocumentException de){
			AntiaLog.fatal("WindowConfiger reset error.");
			de.printStackTrace();
		}
	}
	/**
	 * 从配置文件中构建SingleWindow对象，此方法只提供给缓存类调用。如想取得此类对象，请调用缓存类
	 * @param wid window id
	 * @return	SingleWindow
	 */
	public static SingleWindow getSingleWindow(String wid) {
		StringBuffer sb = new StringBuffer("/all-window/single/window[@id='").append(wid).append("']");
		String path = sb.toString();
		Element element = (Element)doc.selectSingleNode(path);
		if(element == null){
			AntiaLog.error("Single window " + wid + " not config!");
			return null;
		}
		return parseSingleWindow(element);
	}
	
	/**
	 * 从配置文件中构建MultiWindow对象，此方法只提供给缓存类调用。如想取得此类对象，请调用缓存类
	 * @param wid window id
	 * @return	MultiWindow
	 */
	public static MultiWindow getMultiWindow(String wid){
		MultiWindow window = new MultiWindow();
		String path = new StringBuffer("/all-window/multi/pri-sec[@id='").append(wid).append("']").toString();
		Element element = (Element)doc.selectSingleNode(path);
		if(element == null){
			AntiaLog.error("Multi window " + wid + " not config!");
			return null;
		}
		//id
		window.setId(wid);
		//type : one-one many-one
		window.setType(element.attributeValue("type"));
		//layout  布局
		window.setLayout(element.attributeValue("layout"));
		if(window.getLayout() == null || window.getLayout().trim().length() < 1){
			window.setLayout(WindowConst.DEFAULT_LAYOUT);
		}
		//主表
		window.setPrimary(element.attributeValue("primary"));
		//从表
		window.setSecondary(element.attributeValue("secondary"));
		//主表操作
		window.setPrimaryWas(element.attributeValue("primaryWas"));
		//从表操作
		window.setSecondaryWas(element.attributeValue("secondaryWas"));
		//描述
		window.setDesc(element.attributeValue("desc"));
		//关系
		Element temp = element.element("relations");
		List relationElements = temp.elements("relation");
		if(relationElements == null || relationElements.size() < 1){
			AntiaLog.error("MultiWindow config error: not found relations defined.");
			return null;
		}
		HashMap relations = new HashMap();
		for(int i = 0;i<relationElements.size();i++){
			temp = (Element)relationElements.get(i);
			relations.put(temp.attributeValue("primary"), temp.attributeValue("secondary"));
		}
		window.setRelations(relations);
		if(window.getType().equals("oneone") || window.getType().equals("onemany")){
			if(window.getPrimaryWas() == null){
				window.setPrimaryWas(WindowConst.DEFAULT_ONEMANY_ACTION);
			}
		}
		if(window.getSecondaryWas() == null || window.getSecondaryWas().trim().length() < 1){
			window.setSecondaryWas(WindowConst.DEFAULT_ACTION);
		}
		return window;
	}
	/**
	 * 解析Window
	 * 传入Window的XML元素
	 * @param element	Window的XML根元素
	 * @return	SingleWindow
	 */
	private static SingleWindow parseSingleWindow(Element element){
		SingleWindow window = new SingleWindow();
		String winId = element.attributeValue("id");
		window.setId(winId);
		window.setTable(element.attributeValue("table"));
		window.setAction(element.attributeValue("action"));
		if(window.getAction() == null || window.getAction().trim().length() < 1){
			window.setAction(WindowConst.DEFAULT_ACTION);
		}
		window.setType(element.attributeValue("type"));
		//每页的记录数
		String pageSize = element.attributeValue("pageSize");
		int pagesize = (pageSize == null || !Validation.isInt(pageSize)) ? PAGE_SIZE : Integer.parseInt(pageSize);
		window.setPageSize(pagesize);
		//window description
		window.setDesc(element.elementText("desc"));
		//方法
		String function = element.attributeValue("function");
		if(function != null && function.trim().length() > 0) {
            function = function.trim();
            String[] funs = function.split(",");
            List<String> mss = new ArrayList<String>();
            for (String fun : funs) {
                if (fun.equalsIgnoreCase(WindowConst.METHOD_ADD)) {
                    mss.add(WindowConst.METHOD_ADD);
                }else if (fun.equalsIgnoreCase(WindowConst.METHOD_DELETE)) {
                    mss.add(WindowConst.METHOD_DELETE);
                }else if (fun.equalsIgnoreCase(WindowConst.METHOD_QUERY)) {
                    mss.add(WindowConst.METHOD_QUERY);
                }else if (fun.equalsIgnoreCase(WindowConst.METHOD_UPDATE)) {
                    mss.add(WindowConst.METHOD_UPDATE);
                }
            }
            window.setMethods(mss);
        }
		if(window.getMethods() == null || window.getMethods().size() == 0){
			List<String> mes = new ArrayList<String>();
			mes.add(WindowConst.METHOD_ADD);
			mes.add(WindowConst.METHOD_DELETE);
			mes.add(WindowConst.METHOD_UPDATE);
			mes.add(WindowConst.METHOD_QUERY);
			window.setMethods(mes);
		}
		//显示行数
        Element ele1;
        ele1 = element.element("layout");
		if(ele1 != null) {
            Layout layout = window.getLayout();
            layout.setCols(ele1.attributeValue("cols") == null ? SysConf.DEFAULT_DISP_COL : Integer.valueOf(ele1.attributeValue("cols")));
            layout.setCss(ele1.attributeValue("css"));
            layout.setType(ele1.attributeValue("type"));
        }
		//字段 -- 字段
		List eles = element.selectNodes("fields/field");
		if(eles == null || eles.size() < 2){
			AntiaLog.error("Single window " + winId + " fields not config!");
			return null;
		}
		//循环
		String fn;		//字段名
        Cele ec;
		List<Cele> list = new ArrayList<Cele>();
        for(int i = 0;i<eles.size();i++){
			ele1 = (Element)eles.get(i);
			fn = ele1.attributeValue("name");
			ec = ConfigPoolHelper.getElementComsat(window.getTable(), fn);
			ec = DBConfiger.setAttribute(ec,window.getTable(),ele1, ConfigConst.FORM_WINDOW);
			list.add(ec);
		}
		window.setFields(list);
		//设置 formName
		if(window.getFormName() == null){
			window.setFormName(PageRule.getFormName(window.getId()));
		}
		//扩展的属性
		ele1 = element.element("extra");
		window.setExtraColumns(getExpanded(ele1));
		return window;
	}
	/**
	 * 取得扩展字段的列表，传入扩展字段元素
	 * @param element DOM Element <expanded>
	 * @return List<OperateField>
	 */
	public static List<Output> getExpanded(Element element){
		List<Output> list = new ArrayList<Output>();
		if(element == null)return null;
		List eles = element.elements("column");
		Output field;
		if(eles == null || eles.size() < 1)return null;
		for(int i = 0;i<eles.size();i++){
			element = (Element)eles.get(i);
			field = new Output();
			field.setText(element.attributeValue("text"));
			field.setWidth(element.attributeValue("width"));
			field.setLinkUrl(element.attributeValue("linkUrl"));
			field.setOnclick(element.attributeValue("onclick"));
			field.setTitle(element.attributeValue("title"));
			field.setTarget(element.attributeValue("target"));
			list.add(field);
		}
		return list;
	}
}
